package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService implements UserDetailsService {
    public  static Map<String, Object> map = new HashMap<>();
    static {
        com.itheima.pojo.User user1=new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("admin");

        com.itheima.pojo.User user2=new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("1234");
        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户名为："+username);
        User user = (User) map.get(username);
        if (user==null){
            return null;
        }else{
            List<GrantedAuthority> list = new ArrayList<>();//装有权限
            //给用户授权
            list.add(new SimpleGrantedAuthority("permission_A"));//权限
            list.add(new SimpleGrantedAuthority("permission_B"));

            if (username.equals("admin")){
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//角色
            }

            org.springframework.security.core.userdetails.User securityUser= new org.springframework.security.core.userdetails.User(username,"{noop}"+user.getPassword(),list);
            return securityUser;
        }

    }
}
